﻿
function editAgent(button, mode)
{
    var row = $(button).closest(".div-row");
    var cells = row.find(".div-cell");
    if (cells.eq(1).find("input[type=text]").length > 0)
    {
        processUpdate(button);
    }
    
    var divFullName = cells.eq(1).find("div");
    var input = "";
    if (mode == "add")
    {
        input += "<input type=\"hidden\" name=\"jobTitleLinkId\" value=\"\" />";
        input += "<input type=\"hidden\" name=\"agentId\" value=\"\" />";
    }
    input += "<input type=\"text\" name=\"agentFullName\" value=\""+divFullName.text()+"\" onkeydown=\"enter(this, event);\"/>";
    if (divFullName.length > 0)
    {
        divFullName.eq(0).remove();
    }
    if (cells.eq(1).find("input[type=text]").length < 1)
    {
        cells.eq(1).append(input);
    }
    
    
    if (cells.eq(2).find("input[type=text]").length < 1)
    {
        input = "<input type=\"text\" name=\"agentIdentifiedSerial\" value=\""+cells.eq(2).text()+"\" onkeydown=\"enter(this, event);\"/>";
        cells.eq(2).html(input);
    }
    var randomId = "tbx" + randomString();
    if (cells.eq(3).find("input[type=text]").length < 1)
    {
        input = "<input type=\"text\" id=\""+randomId+"\" name=\"agentBirthDate\" value=\""+cells.eq(3).text()+"\" onkeydown=\"enter(this, event);\"/>";
        input += "<script type=\"text/javascript\" language=\"javascript\">new JsDatePick({useMode:2,target:\""+randomId+"\",dateFormat:\"%d/%m/%Y\"});</script>";
        cells.eq(3).html(input);
    }
    if (cells.eq(4).find("input[type=text]").length < 1)
    {
        randomId = "tbx" + randomString();
        input = "<input type=\"text\" id=\""+randomId+"\" name=\"startDate\" value=\""+cells.eq(4).text()+"\" onkeydown=\"enter(this, event);\"/>";
        input += "<script type=\"text/javascript\" language=\"javascript\">new JsDatePick({useMode:2,target:\""+randomId+"\",dateFormat:\"%d/%m/%Y\"});</script>";
        cells.eq(4).html(input);
    }
    if (cells.eq(5).find("input[type=text]").length < 1)
    {
        randomId = "tbx" + randomString();
        input = "<input type=\"text\" id=\""+randomId+"\" name=\"endDate\" value=\""+cells.eq(5).text()+"\" onkeydown=\"enter(this, event);\"/>";
        input += "<script type=\"text/javascript\" language=\"javascript\">new JsDatePick({useMode:2,target:\""+randomId+"\",dateFormat:\"%d/%m/%Y\"});</script>";
        cells.eq(5).html(input);
    }
    
    if (mode=="add" || mode=="enter")
    {
        var table = row.parent();
        var newRow = "<div class=\"div-row\">";
        newRow += "<div class=\"div-cell c0\"></div>";
        newRow += "<div class=\"div-cell c1\">";
        newRow += "<span class=\"add\" onclick=\"editAgent(this, 'add');\"></span>";
        newRow += "<span class=\"enter\" onclick=\"editAgent(this, 'enter');\"></span>";
        newRow += "<input type=\"hidden\" name=\"jobTitleLinkId\" value=\"\" />";
        newRow += "<input type=\"hidden\" name=\"agentId\" value=\"\" />";
        newRow += "<div></div>";
        newRow += "</div>";
        newRow += "<div class=\"div-cell c2\"></div>";
        newRow += "<div class=\"div-cell c2\"></div>";
        newRow += "<div class=\"div-cell c2\"></div>";
        newRow += "<div class=\"div-cell c2\"></div>";
        newRow += "</div>";
        table.append(newRow);
        
        var addButton = cells.eq(1).find(".add");
        if (addButton.length > 0)
        {
            addButton.eq(0).attr("class", "edit");
            addButton.eq(0).attr("onclick", "editAgent(this, 'edit');");
        }
        var enterButton = cells.eq(1).find(".enter");
        if (enterButton.length > 0)
        {
            enterButton.eq(0).attr("class", "remove");
            enterButton.eq(0).attr("onclick", "removeAgent(this);");
        }
    }
    cells.eq(1).find("input[type=text]").focus();
    
    if (mode == "enter")
    {
        var inputFullName = cells.eq(1).find("input[type=text]");
        var inputAgentId = cells.eq(1).find("input[name=agentId]");
        var inputIdentifiedSerial = cells.eq(2).find("input[type=text]");
        var inputBirthdate = cells.eq(3).find("input[type=text]");
        var a = inputFullName.autocomplete({
            serviceUrl:'/AjaxAgent2.aspx',
            params:{event:'type'},
            minChars:1,
            delimiter: /(,|;)\s*/, // regex or character
            dataType: 'json',
            maxHeight:400,
            width:300,
            zIndex: 9999,
            deferRequestBy: 1000, //miliseconds
            noCache: false, //default is false, set to true to disable caching
            // callback function:
            onSelect: function(suggestion){
                //alert('You selected: ' + suggestion.value + ', ' + suggestion.data.identifiedSerial);
                inputAgentId.val(suggestion.data.id);
                inputBirthdate.val(suggestion.data.birthDate);
                inputIdentifiedSerial.val(suggestion.data.identifiedSerial);
            }
            // local autosugest options:
            //lookup: [{value:'abc',data:'111'},{value:'list',data:'222'}],
            /*lookupFilter: function (suggestion, query, queryLowerCase)
            {
                return true;
            }*/
        });
    }
}

function removeAgent(button)
{
    var row = $(button.parentNode.parentNode);
    var jobTitleLinkId = $(button.parentNode).find("input[name=jobTitleLinkId]");
    var agentId = $(button.parentNode).find("input[name=agentId]");
    
    var area = mask();
    $.ajax({
	    async : false,
	    type: 'POST',
	    url: "/AjaxAgent.aspx",
	    data : { 
		    "operation" : "remove_agent", 
		    "jobTitleLinkId" : jobTitleLinkId.val(),
		    "agentId" : agentId.val()
	    }, 
	    success : function (r) {
			if(r.error.length > 0)
			{
			    var error = "";
			    for (var i=0; i<r.error.length; i++)
			    {
			        error += r.error[i] + "\n";
			    }
			    alert(error);
			    if(r.statusLink)
			    {
			        row.remove();
			    }
			}
			else
			{
			    row.remove();
			}
	    }
    })
    .always(function() {
	    unmask(area);
	});
}

function enter(input, evt)
{
    if (evt.keyCode != 13)
    {
        return false;
    }
    processUpdate(input);
    
    return true;
}

function processUpdate(input)
{
    var row = $(input).closest(".div-row");
    var cells = row.find(".div-cell");
    var inputs = row.find("input[type=text]");
    var hiddens = row.find("input[type=hidden]");
    var divFullName = "<div>"+inputs.eq(0).val()+"</div>";
    var jobTitleId = $("a.jstree-clicked").closest("li").attr("id");
    
    var area = mask();
    $.post(
		"/AjaxAgent.aspx", 
		{
		    "jobTitleLinkId" : hiddens.eq(0).val(), 
		    "jobTitleId" : jobTitleId,
		    "agentId" : hiddens.eq(1).val(), 
			"fullName" : inputs.eq(0).val(), 
			"birthDate" : inputs.eq(2).val(), 
			"identifiedSerial" : inputs.eq(1).val(), 
			"startDate" : inputs.eq(3).val(),
			"endDate" : inputs.eq(4).val()
		}, 
		function (r) {
		    if(r.statusLink)
			{
			    hiddens.eq(0).val(r.jobTitleLinkId);
			}
			if(r.statusAgent)
			{
			    hiddens.eq(1).val(r.agentId);
			}
			if(r.error.length > 0)
			{
			    var error = "";
			    for (var i=0; i<r.error.length; i++)
			    {
			        error += r.error[i] + "\n";
			    }
			    alert(error);
			}
			else {
				cells.eq(1).append(divFullName);
                cells.eq(2).text(inputs.eq(1).val());
                cells.eq(3).text(inputs.eq(2).val());
                cells.eq(4).text(inputs.eq(3).val());
                cells.eq(5).text(inputs.eq(4).val());
                inputs.eq(0).remove();
			}
		}
	)
	.always(function() {
	    unmask(area);
	});
}

function selectTreeNode(jobTitleId)
{
    var area = mask();
    $.post(
		"/AjaxAgent.aspx", 
		{ 
			"operation" : "select_node", 
			"jobTitleId" : jobTitleId
		}, 
		function (r) {
		    var table = $(".div-table");
	        var rows = table.find(".div-row");
	        for (var j=rows.length-2; j>0; j--)
	        {
                rows.eq(j).remove();
	        }
	        var header = rows.eq(0);
	        var fm = createFormat(r.agents.length);
		    for (var i=r.agents.length-1; i>=0; i--)
		    {
		        var newRow = "<div class=\"div-row\">";
		        newRow += "<div class=\"div-cell c0\">"+r.agents[i].order+"</div>";
                newRow += "<div class=\"div-cell c1\">";
                newRow += "<span class=\"edit\" onclick=\"editAgent(this, 'edit');\"></span>";
                newRow += "<span class=\"remove\" onclick=\"removeAgent(this);\"></span>";
                newRow += "<input type=\"hidden\" name=\"jobTitleLinkId\" value=\""+r.agents[i].jobTitleLinkId+"\" />";
                newRow += "<input type=\"hidden\" name=\"agentId\" value=\""+r.agents[i].agentId+"\" />";
                newRow += "<div title=\""+r.agents[i].jobTitleName+"\">"+r.agents[i].fullName+"</div>";
                newRow += "</div>";
                newRow += "<div class=\"div-cell c2\">"+r.agents[i].identifiedSerial+"</div>";
                newRow += "<div class=\"div-cell c2\">"+r.agents[i].birthDate+"</div>";
                newRow += "<div class=\"div-cell c2\">"+r.agents[i].startDate+"</div>";
                newRow += "<div class=\"div-cell c2\">"+r.agents[i].endDate+"</div>";
                newRow += "</div>";
                $(newRow).insertAfter(header);
		    }
		}
	)
	.always(function() {
	    unmask(area);
	});
}

